import prompt from './utils/prompt.js';
import Api from './utils/api.js';

// app.js
App({
  appLogin () {
    const _this = this;
    return new Promise((resolve, reject) => {
      // 登录
      wx.login({
        success: async res => {
          if (res.code) {
            const myRes = await Api.login(res.code);
            if (myRes) {
              this.globalData.sessionKey = myRes.message.sessionKey;
              const curPage = getCurrentPages()[getCurrentPages().length - 1].route;
              if (curPage !== 'pages/register/register') {
                if (!myRes.message.loginUser) { // 未注册
                  prompt.showModal('请关注公众号“奥拉前沿”进行注册');
                } else {
                  this.globalData.userInfo = myRes.message.loginUser;
                }
              }
            }
          } else {
            prompt.showToast('小程序登录失败，请稍后再试');
          }
          _this.getUserInfo();
          resolve();
        }
      });
    });
  },

  // 查询用户个人信息
  getUserInfo () {
    wx.getUserInfo({
      withCredentials: false,
      lang: 'zh_CN',
      success: (result) => {
        this.globalData.avatarUrl = result.userInfo.avatarUrl;
      }
    });
  },

  // web-view 跳转函数
  toWebView (pIdx) {
    wx.navigateTo({
      url: '/pages/webView/webView?pIdx=' + pIdx
    });
  },

  globalData: {

    /* 刷新状态 */
    refresh_myOrder: false,
    refresh_myApproval: false,

    userInfo: null,
    sessionKey: null,
    avatarUrl: '', // 当前用户头像地址

    orderDetail: {}, // 当前详情/审核申请对象
    myOrders: [], // 我的预约列表
    myApproval: {}, // 我的审核数据
    projections: [] // 项目动态列表
  }
});
